// 首页 相关的路由
var express = require('express');
var router = express.Router();
// 导入数据库连接对象
var query = require("../db/db.js");

// 前端在用到这个文件中的接口时，就检查是否携带token
// router.use(function timeLog(req, res, next) {
//     console.log('Time: ', Date.now())
//     //模块路由中检测是否携带了 token
//     // if (!req.auth) {
//     //     return res.send({
//     //         status: 403,
//     //         message: "缺少token"
//     //     });
//     // }
//     // next()
// })

// 导入模型
const { users, comment } = require("../model/comment.js");
const { where } = require('sequelize');

// 单个文章底下的评论
router.get("/article_comment/:articleId", async (req, res) => {
    const { articleId } = req.params;
    const { userId } = req.query;

    // 验证输入数据
    // if (!userId || !articleId) {
    //     return res.status(400).json({ code: -1, msg: "缺少必要的参数" });
    // }
    if (!articleId) {
        return res.status(400).json({ code: -1, msg: "缺少必要的参数" });
    }

    try {
        // 验证 articleId 和 userId 是否为数字
        if (isNaN(Number(articleId)) || isNaN(Number(userId))) {
            return res.status(400).json({ code: -1, msg: "参数必须是数字" });
        }

        // 查找用户
        const user = await users.findOne({
            attributes: ['username'],
            where: {
                id: Number(userId)
            }
        });

        // if (!user) {
        //     return res.status(404).json({ code: -1, msg: "用户不存在" });
        // }

        // 查找文章对应的评论
        const commentsData = await comment.findAll({
            where: {
                article_id: Number(articleId)
            }
        });

        // 返回成功响应
        if (user) {
            res.json({
                code: 0,
                msg: "你已经登录，评论获取成功",
                userData: { username: user.username },
                commentData: commentsData
            });
        } else {
            res.json({
                code: 0,
                msg: "你还未登录，评论获取成功",
                commentData: commentsData
            });
        }

    } catch (error) {
        console.error(error);
        res.status(500).json({ code: -1, msg: "评论查询失败" });
    }
});

// 用户的评论功能
router.post("/tocomment", async (req, res) => {
    const { user_id, content, article_id } = req.body;
    // 验证输入数据
    if (!user_id || !content || !article_id) {
        return res.status(400).json({ code: -1, msg: "缺少必要的参数" });
    }
    try {
        // 查找用户
        const user = await users.findOne({
            attributes: ['username'],
            where: {
                id: user_id
            }
        });

        if (!user) {
            return res.status(404).json({ code: -1, msg: "用户不存在" });
        }
        // 获取当前时间作为评论发布时间
        let date = new Date();
        let time = date.getTime();
        console.log(time)
        // 创建评论
        const commentResult = await comment.create({
            user_id: user_id,
            content: content,
            article_id: article_id,
            ctime: time,
            state:0
        });
        // 获取年、月、日、时、分、秒
        const year = date.getFullYear();
        const month = date.getMonth() + 1; // getMonth() 返回的月份是从 0 开始的
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        const seconds = date.getSeconds();

        // 将月、日、时、分、秒格式化为两位数
        const formattedMonth = month < 10 ? `0${month}` : month;
        const formattedDay = day < 10 ? `0${day}` : day;
        const formattedHours = hours < 10 ? `0${hours}` : hours;
        const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes;
        const formattedSeconds = seconds < 10 ? `0${seconds}` : seconds;

        // 构建最终的日期字符串
        const formattedCtime = `${year}-${formattedMonth}-${formattedDay} ${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
        // 返回成功响应
        res.json({
            code: 0,
            msg: "评论发布成功！",
            username: user.username,
            // ctime: ctime.toISOString() // 将时间转换为ISO字符串格式返回
            ctime: formattedCtime
        });
    } catch (error) {
        console.error(error);
        res.status(500).json({ code: -1, msg: "评论发布失败" });
    }
});


//推荐列表
// /home/recommend
router.get("/recommend", function (req, res) {
    let sql = "SELECT id,title,sub_title,`view`,`like`,username,pic,ctime from article where recommend=1 order by id desc limit 6";
    query(sql, function (err, result) {
        if (err) {
            console.log(err)
            res.json({ msg: "查询出错啦", code: -1 })
        }
        res.json({ msg: "ok", code: 0, result })
    })
})

//右侧点赞
// /home/like
router.get("/like", function (req, res) {
    let sql = "SELECT id,title,sub_title,`view`,`like`,username from article order by `like` desc limit 6";
    query(sql, function (err, result) {
        if (err) {
            console.log(err)
            res.json({ msg: "查询出错啦", code: -1 })
        }
        res.json({ msg: "ok", code: 0, result })
    })
})


//右侧最新
// /home/new
router.get("/new", function (req, res) {
    let sql = "SELECT id,title,sub_title,`view`,`like`,username from article order by id desc limit 6";
    query(sql, function (err, result) {
        if (err) {
            console.log(err)
            res.json({ msg: "查询出错啦", code: -1 })
        }
        res.json({ msg: "ok", code: 0, result })
    })
})


//导出路由对象
module.exports = router;
// exports.router = {router};